import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, DatePicker, Badge, Select } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './DevFix.less';
import UpLoadForm from '../../components/UpLoadForm/UpdateOtaFile';

const FormItem = Form.Item;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const CreateForm = Form.create()(UpLoadForm);

@connect(({ devupdate }) => ({
    devupdate,
}))
@Form.create()
export default class DevUpdate extends PureComponent {
    state = {
        selectedRows: [],
        record: {},
        modalVisible: false,
    };

    componentDidMount() {
        const payload = {};
        const { dispatch } = this.props;
        dispatch({
            type: 'devupdate/fetch',
            payload,
        });
    }

    onbind = record => {
        this.setState({ record });
        this.handleModalVisible(true);
    };

    handleModalVisible = (flag) => {
        // console.log('modal visible', flag, opType);
        this.setState({
            modalVisible: !!flag,
        });
    };

    getFromValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;

            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }
            //console.log('postvalue', postvalue);
            if (postvalue.date && postvalue.date.length > 0) {
                const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
                const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
                postvalue = {
                    ...postvalue,
                    startSubDate,
                    endSubDate,
                };
                delete postvalue.date;
            }
        });
        return postvalue;
    };

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = { ...obj };
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});
        const postvalue = this.getFromValue();
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'devupdate/fetch',
            payload: params,
        });
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFromValue();
        dispatch({
            type: 'devupdate/fetch',
            payload: postvalue,
        });
    };

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={3} sm={24}>
                        <FormItem>
                            {this.props.form.getFieldDecorator('otaType',
                            )(
                                <Select style={{ width: 200 }} allowClear placeholder="文件版本">
                                    <Select.Option value={0}>测试版本</Select.Option>
                                    <Select.Option value={1}>生产版本</Select.Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>


                    <Col md={6} sm={24}>
                        <Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
                            查询
                        </Button>

                        <Button type="primary" style={{ marginRight: 10 }} onClick={() => this.handleModalVisible(true)}>
                            上传
                        </Button>

                    </Col>
                </Row>
            </Form>
        );
    }

    render() {
        // //console.log('task', this.props.task);
        const { devupdate, loading } = this.props;
        const { selectedRows } = this.state;
        const columns = [
            {
                title: '版本说明',
                dataIndex: 'verDescr',
            },
            {
                title: '文件名',
                dataIndex: 'otaFileName',
            },

            {
                title: '文件大小',
                dataIndex: 'fileSize',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
            },
            {
                title: '备注',
                dataIndex: 'remark',
            },

            {
                title: '操作',
                render: (text, record) => (
                    <Fragment>
                        <a href={record.otaFileUrl}>下载</a>
                    </Fragment>
                ),
            },
        ];

        return (
            <PageHeaderLayout title="设备升级">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                        <StandardTable
                            rowKey="setId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={devupdate}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <CreateForm
                    handleModalVisible={this.handleModalVisible}
                    modalVisible={this.state.modalVisible}
                    dispatch={this.props.dispatch}
                    handleSearch={this.handleSearch}
                />
            </PageHeaderLayout>
        );
    }
}
